/*
 * Copyright 2022 Huawei Cloud Computing Technology Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.huawei.cloudphone.utils;

import com.huawei.cloudphone.common.CASLog;

import java.util.HashMap;

import static com.huawei.cloudphone.utils.CasConstantsUtil.BITRATE;
import static com.huawei.cloudphone.utils.CasConstantsUtil.STREAM_HEIGHT;
import static com.huawei.cloudphone.utils.CasConstantsUtil.STREAM_WIDTH;

import android.media.MediaCodecList;
import android.media.MediaFormat;

public class CasMediaUtils {

    public static final String TAG = "CasMediaUtils";
    public static final int BITRATE_MIN = 100000;
    public static final int BITRATE_MAX = 10000000;
    public static final int MIN = 240;
    public static final int MAX = 4096;
    public static final int TIMES = 8;

    public static boolean isValidMediaConfig(HashMap<String, String> mediaConfig) {
        if (mediaConfig == null || mediaConfig.size() == 0) {
            CASLog.e(TAG, "media config is empty");
            return false;
        }

        // 校验码率
        if (mediaConfig.containsKey(BITRATE)) {
            int bitrate = Integer.parseInt(mediaConfig.get(BITRATE));
            if (bitrate < BITRATE_MIN || bitrate > BITRATE_MAX) {
                CASLog.e(TAG, "bitrate is invalid");
                return false;
            }
        }

        // 校验分辨率
        boolean containsVirtualWidth = mediaConfig.containsKey(STREAM_WIDTH);
        boolean containsVirtualHeight = mediaConfig.containsKey(STREAM_HEIGHT);
        if (containsVirtualWidth && containsVirtualHeight) {
            int virtualWidth = Integer.parseInt(mediaConfig.get(STREAM_WIDTH));
            int virtualHeight = Integer.parseInt(mediaConfig.get(STREAM_HEIGHT));
            if (virtualWidth > virtualHeight || virtualWidth < MIN || virtualWidth > MAX || virtualWidth % TIMES != 0
                    || virtualHeight < MIN || virtualHeight > MAX || virtualHeight % TIMES != 0) {
                CASLog.e(TAG, "the virtual width or virtual height is valid");
                return false;
            }
        } else if (containsVirtualHeight || containsVirtualWidth) {
            CASLog.e(TAG, "virtual width or virtual height is not included");
            return false;
        } else {
            CASLog.i(TAG, "virtual width and virtual height are not found");
        }
        return true;
    }

}